#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "dtk_types.h"
#include "dtk_debug.h"
#include "dtk_list.h"
#include "dtk_single.h"

const DString DTK_TYPE_SINGLE = "DTKSingle";

static void single_release (DTKActor* self)
{
    DTKSingle* single = (DTKSingle*) self;
    DTK_TYPE_ASSERT(single, DTK_TYPE_SINGLE);
    
    dtk_actor_finalize (single->content);
    return;
}

static void single_show_all(DTKActor* self)
{
    DTKSingle* single = (DTKSingle*) self;
    
    DTK_TYPE_ASSERT(single, DTK_TYPE_SINGLE);

    dtk_actor_show_all(single->content);
    
    return;
}

static void single_hide_all(DTKActor* self)
{
    DTKSingle* single = (DTKSingle*) self;
   
    DTK_TYPE_ASSERT(single, DTK_TYPE_SINGLE);
    
    dtk_actor_hide_all(single->content);
    return;
}

static void single_remove_actor(DTKActor* self, DTKActor* actor)
{
    DTKSingle* single = (DTKSingle*) self;
   
    DTK_TYPE_ASSERT(single, DTK_TYPE_SINGLE);

    if (actor != single->content)
    {
        return;
    }

    dtk_layout_remove (actor->layout);
    dtk_actor_unparent (single->content);
    dtk_actor_update(self, NULL, DTK_FALSE);
    return;
}

static void single_add_actor(DTKActor* self, DTKActor* actor)
{
    DTKSingle* single = (DTKSingle*) self;
    if (NULL == actor)
    {
        return;
    }

    DTK_TYPE_ASSERT(single, DTK_TYPE_SINGLE);

    if (single->content)
    {
        single_remove_actor(self, single->content);
    }
    
    dtk_layout_add (self->layout, actor->layout);
    single->content = actor;
    dtk_actor_set_parent(actor, self);
    dtk_actor_update(actor, NULL, DTK_FALSE);
    return;
}

DTKActor* dtk_single_init (DInt size, DString type, DTKActorCaps caps)
{
    DTKActor* actor;
    DTKSingle* single;
    DTKActorCallback* funcs;

    if (size < sizeof (DTKSingle))
    {
        return NULL;
    }

    actor = dtk_actor_init (size, type, caps);

    single = (DTKSingle*) actor;
    single->type = DTK_TYPE_SINGLE;

    funcs = DTK_ACTOR_CALLBACK(actor);

    funcs->release  = single_release;
    funcs->add      = single_add_actor;
    funcs->remove   = single_remove_actor;
    funcs->show_all = single_show_all;
    funcs->hide_all = single_hide_all;

    return actor;    
}
